package com.fs.web.base.annotation;

import com.fs.common.pojo.Log;
import com.fs.common.pojo.User;
import com.fs.common.baseMapper.LogMapper;
import com.fs.web.base.utils.ApplicationUtils;
import com.fs.web.base.vo.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

/**
 * @author ACE
 * @desc 切点类
 * @creationTime 2019-02-28 15:13
 * @projectName gps-root
 * @packageName com.fs.base.annotation
 */
@Aspect
@Component
@Slf4j
@SuppressWarnings("all")
public class SystemLogAspect {
    //注入Service用于把日志保存数据库，实际项目入库采用队列做异步
    @Autowired
    private LogMapper logMapper;

    //Controller层切点
    @Pointcut("@annotation(com.fs.web.base.annotation.SystemControllerLog)")
    public void controllerAspect(){
    }

    /**
     * @Description  后置通知  用于拦截Controller层记录用户的操作
     */
    @Before("controllerAspect()")
    public void doBefore(JoinPoint joinPoint){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();
        //读取session中的用户
        LoginUser loginUser = ApplicationUtils.getUser();
        if(loginUser == null){
            return;
        }
        User user = loginUser.getUser();

        if(user == null){
            return;
        }

        String ip = ApplicationUtils.getRemoteHost();

        try {
            //*========控制台输出=========*//
            /*System.out.println("==============后置通知开始==============");
            System.out.println("请求方法" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName()));
            System.out.println("方法描述：" + getControllerMethodDescription(joinPoint));
            System.out.println("请求人："+user.getName());
            System.out.println("请求ip："+ip);*/

            //*========数据库日志=========*//
            SystemControllerLog controllerLog = getControllerMethodDescription(joinPoint);
            Log log = new Log(user.getComId(),ip,joinPoint.getSignature().getName(),controllerLog.type().getValue(),controllerLog.description(),user.getId());
            //保存数据库
            logMapper.insert(log);
        }catch (Exception e){
            //记录本地异常日志
            log.error("==前置通知异常==");
            log.error("异常信息：{}",e.getMessage());
        }
    }

    /**
     * @author ACE
     * @Description  获取注解中对方法的描述信息 用于Controller层注解
     */
    public static SystemControllerLog getControllerMethodDescription(JoinPoint joinPoint) throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();//目标方法名
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        SystemControllerLog systemControllerLog = null;
        for (Method method:methods) {
            if (method.getName().equals(methodName)){
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length==arguments.length){
                    systemControllerLog = method.getAnnotation(SystemControllerLog.class);
                    break;
                }
            }
        }
        return systemControllerLog;
    }
}
